<template>
  <Dialog title="牵线" v-model="dialogVisible" width="600">
    <div class="flex text-center mx3">
      <div class="w160px shrink-0 relative">
        <div>{{ activeUserSex }}</div>
        <el-avatar class="mt2" :size="100" :src="activeUser?.avatar" />
        <div class="font-bold font-size-4 mt2 mb.5">{{ activeUser?.nickname }}</div>
        <small class="color-gray">(ID: {{ activeUser?.id }})</small>
      </div>
      <div class="-mx50px">
        <img class="w100% mt50px" :src="heartIcon" />
      </div>
      <div class="w160px shrink-0">
        <div>{{ receiveUserSex }}</div>
        <div>
          <el-avatar class="mt2" :size="100" :src="receiveUser?.avatar" />
          <div class="font-bold font-size-4 mt2 mb.5">{{ receiveUser?.nickname }}</div>
          <small class="color-gray">(ID: {{ receiveUser?.id }})</small>
        </div>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="0"
          v-loading="formLoading"
        >
          <el-form-item prop="receiveId" class="mt36px">
            <el-input v-model="formData.receiveId" placeholder="请输入用户ID" clearable>
              <template #append>
                <el-button :icon="Search" @click="handleReceiveUser" />
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button
        @click="(dialogVisible = false), (receiveUser = null), (formData.receiveId = undefined)"
        >取 消</el-button
      >
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import heartIcon from '../../../../assets/icon/heart.png'
import * as MatchmakerStringingApi from '@/api/blind/maker/matchmakerStringing/index.ts'
import * as UserApi from '@/api/member/user'
import { useIMStoreWithOut } from '@/store/modules/im'
import { useUserStoreWithOut } from '@/store/modules/user'
import { onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { TUIStore, StoreName, IConversationModel } from '@tencentcloud/chat-uikit-engine'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()

defineOptions({ name: 'MemberUser' })

const userID = ref('')

TUIStore.watch(StoreName.CONV, {
  currentConversation: (conversation: IConversationModel) => {
    userID.value = conversation?.userProfile?.userID
    console.log(userID)
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  activeId: undefined, // 主动牵线人id
  receiveId: undefined, // 被动动牵线人id
  manId: undefined, // 会员id（男）
  womanId: undefined, // 会员id（女）
  matchmakerId: undefined, // 红娘id
  stringingStatus: 0
})
const formRules = reactive({
  receiveId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const activeUser = ref()
const receiveUser = ref()

interface User {
  userID: number
  nick: string
  avatar: string
}

const dialogVisible = ref(false) // 弹窗的是否展示

const formatSex = (val) => {
  let sex

  switch (val) {
    case 1:
      sex = '男方'
      break

    case 2:
      sex = '女方'
      break

    default:
      sex = '-'
      break
  }

  return sex
}

const activeUserSex = computed(() => {
  return formatSex(activeUser.value?.sex)
})

const receiveUserSex = computed(() => {
  return formatSex(receiveUser.value?.sex)
})

// 获取用户详情
const handleReceiveUser = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 查询用户信息
  receiveUser.value = await UserApi.getUser(formData.value.receiveId)
  if (!receiveUser.value) {
    message.success(`用户不存在，请重新输入`)
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (!receiveUser) {
    message.success(`用户不存在，请重新输入`)
    return
  }

  if (activeUser.value.id === receiveUser.value.id) {
    message.success(`牵线双方不能为同一人`)
    return
  }

  if (activeUserSex.value === receiveUserSex.value) {
    message.success(`同性之间无法牵线，请重新选择用户`)
    return
  }

  formData.value.activeId = userID.value
  if (receiveUserSex.value === '男方') {
    formData.value.manId = receiveUser.value?.id
    formData.value.womanId = activeUser.value?.id
  }
  if (receiveUserSex.value === '女方') {
    formData.value.manId = activeUser.value?.id
    formData.value.womanId = receiveUser.value?.id
  }
  formData.value.matchmakerId = wsCache.get('IMUserID')
  // formData.value.matchmakerId = useIMStoreWithOut().getIMUserID

  console.log(formData)

  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MatchmakerStringingApi.MatchmakerStringingVO
    await MatchmakerStringingApi.createMatchmakerStringing(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  // 获取用户详情
  activeUser.value = await UserApi.getUser(userID.value)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹
</script>
